import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Rating } from '@/types'
import { ratingAPI } from '@/services/api'

export const useRatingsStore = defineStore('ratings', () => {
  // 状态
  const ratings = ref<Rating[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 获取用户评分列表
  const fetchRatings = async () => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await ratingAPI.getRatings()
      // 确保ratings.value始终是数组
      if (Array.isArray(response.data)) {
        ratings.value = response.data
      } else if (response.data && Array.isArray(response.data.results)) {
        // 处理分页响应
        ratings.value = response.data.results
      } else {
        ratings.value = []
      }
      
      return ratings.value
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取评分列表失败'
      ratings.value = [] // 确保出错时也是数组
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 创建评分
  const createRating = async (ratingData: { movie: number; rating: number }) => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await ratingAPI.createRating(ratingData)
      const newRating = response.data
      
      // 添加到本地状态
      ratings.value.push(newRating)
      
      return newRating
    } catch (err: any) {
      error.value = err.response?.data?.detail || '创建评分失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 更新评分
  const updateRating = async (id: number, ratingData: { rating: number }) => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await ratingAPI.updateRating(id, ratingData)
      const updatedRating = response.data
      
      // 更新本地状态
      const index = ratings.value.findIndex(r => r.id === id)
      if (index !== -1) {
        ratings.value[index] = updatedRating
      }
      
      return updatedRating
    } catch (err: any) {
      error.value = err.response?.data?.detail || '更新评分失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 删除评分
  const deleteRating = async (id: number) => {
    try {
      isLoading.value = true
      error.value = null
      
      await ratingAPI.deleteRating(id)
      
      // 从本地状态中移除
      ratings.value = ratings.value.filter(r => r.id !== id)
      
      return true
    } catch (err: any) {
      error.value = err.response?.data?.detail || '删除评分失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取特定电影的用户评分
  const getUserRatingForMovie = (movieId: number): Rating | null => {
    if (!Array.isArray(ratings.value)) {
      return null
    }
    return ratings.value.find(r => r.movie === movieId) || null
  }

  // 检查用户是否已评分某电影
  const hasUserRatedMovie = (movieId: number): boolean => {
    if (!Array.isArray(ratings.value)) {
      return false
    }
    return ratings.value.some(r => r.movie === movieId)
  }

  // 为电影评分（创建或更新）
  const rateMovie = async (movieId: number, rating: number) => {
    const existingRating = getUserRatingForMovie(movieId)
    
    if (existingRating) {
      // 更新现有评分
      return await updateRating(existingRating.id, { rating })
    } else {
      // 创建新评分
      return await createRating({ movie: movieId, rating })
    }
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 重置状态
  const resetState = () => {
    ratings.value = []
    error.value = null
  }

  return {
    // 状态
    ratings,
    isLoading,
    error,
    // 方法
    fetchRatings,
    createRating,
    updateRating,
    deleteRating,
    getUserRatingForMovie,
    hasUserRatedMovie,
    rateMovie,
    clearError,
    resetState,
  }
})